Vue.component('show-detail', {
    template: `<el-dialog title="明细查询" :visible.sync="visibleDialog" width="80vw">
    <el-table :data="tableData" stripe border min-height="50vh" style="width: 100%">
        <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
        <el-table-column align="center" prop="Supplier_Article_SerialNumber" show-overflow-tooltip label="供应商品内码"></el-table-column>
        <el-table-column align="center" prop="Supplier_Name" show-overflow-tooltip label="供应商名称"></el-table-column>
        <el-table-column align="center" prop="Article_Name" show-overflow-tooltip label="商品名称"></el-table-column>
        <el-table-column align="center" prop="Specifications_Name" show-overflow-tooltip label="规格名称"></el-table-column>
        <el-table-column align="center" prop="Purchase_Unit_Price" show-overflow-tooltip label="采购价格"></el-table-column>
    </el-table>
    <el-pagination style="margin-top: 5px;" background @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="form.page" :page-sizes="[10, 20, 30, 50]"
        :page-size="form.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:visible',false)">返回</el-button>
    </span></el-dialog>`,
    props: ['id','visible'],
    data() {
        return {
            visibleDialog: false,
            refreshDialog: false,
            tableData: [],
            form: {
                SQLSerialNumber: "P_business_purchase_unitprice_detail",
                PaginationNumber: 1,
                RowAmount: 10,
                ExtensionCondition: '',
                Condition: ''
            },
            total: 0,
        }
    },
    watch: {
        visible() {
            this.visibleDialog = this.visible
        },
        visibleDialog(val) {
            this.$emit('update:visible', val)
            if (val) {
                this.form.Condition = window.btoa(unescape(encodeURIComponent("%"+this.id+"%")));
                this.getList(this.form)
            }
        },
    },
    methods: {
        handleSizeChange(val) {
            this.form.PaginationNumber = 1;
            this.form.RowAmount = val;
            this.getList(this.form)
        },
        handleCurrentChange(val) {
            this.form.PaginationNumber = val;
            this.getList(this.form)
        },
        getList(data) {
            const that = this
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    that.tableData = Result.Rows;
                    that.total = Result.TotalRows;
                },
                complete: function (XMLHttpRequest) {
                    that.refreshDialog = false;
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        }
    }
})
new Vue({
    el: '#app',
    data() {
        return {
            form: {
                SQLSerialNumber: "P_business_purchase_unitprice",
                PaginationNumber: 1,//页数
                RowAmount: 15,//每页数据条数
                Supplier_Name:'',
                ExtensionCondition:'',
                Start_Date:'0',
                Condition:''
            },
            total:0,
            tableData: [],	//表格数据
            dialogVisible:false,
            Purchase_Unit_Price_SerialNumber:'',
            Start_Date:[{
                label:'开始时间正序',
                value:'0'
            },{
                label:'开始时间倒叙',
                value:'1'
            }],
            loading:false,
        }
    },
    mounted() {
        this.getList(this.form);//前端分页
    },
    methods: {
        onSerach() {			//查询方法
            this.form.PaginationNumber = 1;
            this.getList(this.form)
        },
        Add() {
            window.location.href = './add.html'
        },
        handleSizeChange(val) {
            this.form.PaginationNumber = 1;
            this.form.RowAmount = val;
            this.getList(this.form)
        },
        handleCurrentChange(val) {
            this.form.PaginationNumber = val;
            this.getList(this.form)
        },
        getList(form) {//换页方法
            const that = this
            let data = deepClone(form);
            if (data.Start_Date != "") {
                if (data.Start_Date == "0") {
                    data.ExtensionCondition =  window.btoa(unescape(encodeURIComponent("ORDER BY business_purchase_unitprice.Start_Date DESC")));
                } else if (data.Start_Date == "1"){
                    data.ExtensionCondition =  window.btoa(unescape(encodeURIComponent("ORDER BY business_purchase_unitprice.Start_Date")));
                }
            }
            $.ajax({
                headers:requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    that.tableData = Result.Rows;
                    that.total = Result.TotalRows;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        Daily(){//执行单手动更新
            const that = this;
            this.$confirm('此操作将生成今日执行单（已存在的不会更新）, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.loading = true;
                $.ajax({//更新今日执行单
                    headers: requestHeaders(),
                    url: `${BASE_URL2}/article/generateDailyArticlePurchasePrice`,
                    type: 'GET',
                    complete: function (XMLHttpRequest) {
                        that.loading = false;
                        if (XMLHttpRequest.status == 200) {
                            that.$message.success("采购价格执行单更新成功")
                        } else {
                            that.$message.error("采购价格执行单更新失败")
                        }
                    }
                })
            }).catch(() => {});
        },
        Export(row){
            const that = this;
            let Purchase_Unit_Price_SerialNumber = row.Purchase_Unit_Price_SerialNumber?row.Purchase_Unit_Price_SerialNumber:'';
            $.ajax({
                headers:requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data:{
                    SQLSerialNumber: 'P_business_purchase_unitprice_detail',
                    Condition: window.btoa(unescape(encodeURIComponent("%"+Purchase_Unit_Price_SerialNumber+"%"))),
                    ExtensionCondition: '',
                },
                success: function (Result) {
                    if (Result.length > 0) {
                        const wb = XLSX.utils.book_new();
                        const ws_data = [["采购价格单编号","采购价格明细编号","开始时间","结束时间","商品名称","规格名称","供应商","采购价格"]]
                        Result.forEach(item => {
                            ws_data.push([
                                item.Purchase_Unit_Price_SerialNumber,
                                item.Purchase_Unit_Price_Detail_SerialNumber,
                                item.Start_Date,
                                item.End_Date,
                                item.Article_Name,
                                item.Specifications_Name,
                                item.Supplier_Name,
                                item.Purchase_Unit_Price
                            ])
                        })
                        const ws = XLSX.utils.aoa_to_sheet(ws_data);
                        ws['!cols'] = [];
                        ws_data[0].forEach(item => {
                            ws['!cols'].push({ alignment: { horizontal: "center" }, wpx: 150 });
                        })
                        XLSX.utils.book_append_sheet(wb, ws, "采购价格单");
                        XLSX.writeFile(wb, '采购价格单' + (+new Date()) + ".xlsx");
                        that.$message({
                            message: '已导出该采购价格单！',
                            type: 'success'
                        })
                    }else {
                        that.$message({
                            message: '暂无可导出的数据',
                            type: 'warning'
                        })
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        config(command,row){
            if (command == "Remove") {
                this.Remove(row)
            }else if (command == "Export"){
                this.Export(row)
            }
        },
        downloadTemplate(command){
            if (command == "purchase") {
                window.location.href = './download/导入采购价格单模板.xlsx';
            } 
        },
        importTemplate(command){
            if (command == "purchase") {
                window.location.href = './import.html';
            }
        },
        Show(Purchase_Unit_Price_SerialNumber) {
            this.Purchase_Unit_Price_SerialNumber = Purchase_Unit_Price_SerialNumber
            this.dialogVisible = true
        },
        Remove(row) {
            const that = this
            this.$confirm('警告！此操作将删除该操作员, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                let obj = deepClone(row);
                obj.Row_Status = '1';
                $.ajax({
                    headers:requestHeaders(),
                    url: `${BASE_URL2}/generalBusiness/generalSave`,
                    type: 'POST',
                    data: {
                        Data: JSON.stringify({ 
                            Modify: { business_purchase_unitprice: [obj] } ,
                            Add: { base_operation_log: [generateLog('删除采购价格单', '平台端操作', 'business_purchase_unitprice', JSON.stringify({ Modify: { business_purchase_unitprice:[obj] } }))] }
                        })
                    },
                    success: function (res) {
                        if (res.Status === 'success') {
                            that.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            that.getList(that.form);
                        } else {
                            that.$message.error("删除失败，请稍后再试")
                        }
                    },
                    complete: function (XMLHttpRequest) {
                        that.loading = false
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json"
                })
            }).catch(() => {});
        }

    },
})